package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.DSAPublicKey;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import util.SamlException;
import util.Util;

/**
 * Servlet implementation class ProcessSAMLResponseServlet
 */
public class ProcessSAMLResponseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private final String samlResponseTemplateFile = "SamlResponseTemplate.xml";

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		HttpSession session = request.getSession();
		
		session.removeAttribute("processType");
		
		String user = (String) session.getAttribute("user");
		String acsURL = (String) session.getAttribute("acsURL");
		String requestId = (String) session.getAttribute("requestId");
		String issueInstant = (String) session.getAttribute("issueInstant");

		// if ("sso".equals(processType)) {
		String notBefore = Util.getNotBeforeDateAndTime();
		String notOnOrAfter = Util.getNotOnOrAfterDateAndTime();
		try {
			String responseXmlString = createSamlResponse(user, notBefore,
					notOnOrAfter, requestId, acsURL);

			String publicKeyFilePath = getServletContext().getRealPath(
					"./keys/DSAPublicKey01.key");
			String privateKeyFilePath = getServletContext().getRealPath(
					"./keys/DSAPrivateKey01.key");

			DSAPublicKey publicKey = (DSAPublicKey) Util.getPublicKey(
					publicKeyFilePath, "DSA");
			DSAPrivateKey privateKey = (DSAPrivateKey) Util.getPrivateKey(
					privateKeyFilePath, "DSA");

			String signedSamlResponse = ProcessRequestServlet.signResponse(
					responseXmlString, publicKey, privateKey);

			// String
			// encodeResponse=RequestUtil.encodeMessage(signedSamlResponse);

			// String
			// decodeReponse=ProcessResponseServlet.decodeAuthnRequestXML(encodeResponse);

			PrintWriter out = response.getWriter();

			out.println("<html><body onload='document.forms[0].submit();'><form style='display:none' method='post' action='"
							+ acsURL + "'>");
			out.println("<input name='test' value='aa'><input name='SAMLResponse' value='"
							+ responseXmlString + "'></form></body></html>'");

		} catch (SamlException e) {
			e.printStackTrace();
		}

	}

	/*
	 * Generates a SAML response XML by replacing the specified username on the
	 * SAML response template file. Returns the String format of the XML file.
	 */
	private String createSamlResponse(String authenticatedUser,
			String notBefore, String notOnOrAfter, String requestId,
			String acsURL) throws SamlException {
		String filepath = getServletContext().getRealPath(
				"templates/" + samlResponseTemplateFile);
		String samlResponse = Util.readFileContents(filepath);
		samlResponse = samlResponse.replace("<USERNAME_STRING>",
				authenticatedUser);
		samlResponse = samlResponse.replace("<RESPONSE_ID>", Util.createID());
		samlResponse = samlResponse.replace("<ISSUE_INSTANT>", Util
				.getDateAndTime());
		samlResponse = samlResponse.replace("<AUTHN_INSTANT>", Util
				.getDateAndTime());
		samlResponse = samlResponse.replace("<NOT_BEFORE>", notBefore);
		samlResponse = samlResponse.replace("<NOT_ON_OR_AFTER>", notOnOrAfter);
		samlResponse = samlResponse.replace("<ASSERTION_ID>", Util.createID());
		samlResponse = samlResponse.replace("<REQUEST_ID>", requestId);
		samlResponse = samlResponse.replace("<ACS_URL>", acsURL);
		return samlResponse;

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
